{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from bitarray import bitarray\n",
    "import pickle\n",
    "import numpy as np\n",
    "import torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "def as_bit_tensor(tensor, num_bits=2):\n",
    "    \"\"\"Cast a tensor of int type into binary\n",
    "    \"\"\"\n",
    "    shape = tensor.shape\n",
    "    array = tensor.reshape(-1).numpy()\n",
    "    bool_arrays = [np.zeros_like(array, dtype=np.bool) for _ in range(num_bits)]     # construct a list of boolean array\n",
    "    for i, bit in enumerate(reversed(range(num_bits))):\n",
    "        idx = array >= (2**bit)\n",
    "        bool_arrays[i][idx] = True\n",
    "        array = array - (2**bit) * idx\n",
    "    bit_arrays = [bitarray(bool_ten.tolist()) for bool_ten in bool_arrays]\n",
    "    \n",
    "    return {'s': shape, 'd': bit_arrays}\n",
    "\n",
    "\n",
    "def as_int_tensor(bit_tensor):\n",
    "    tensor = torch.zeros(bit_tensor['s'], dtype=torch.int)\n",
    "    for i, bt in enumerate(reversed(bit_tensor['d'])):\n",
    "        tensor += (2 ** i) * torch.tensor(bt.tolist(), dtype=torch.bool).reshape(bit_tensor['s'])\n",
    "    return tensor\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor(0)\n"
     ]
    }
   ],
   "source": [
    "a = torch.randint(4, (100, 1024))\n",
    "b = as_bit_tensor(a, num_bits=2)\n",
    "c = as_int_tensor(b)\n",
    "print(torch.sum(torch.abs(a-c)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [],
   "source": [
    "pickle.dump(a, open('origin_tensor', 'wb')) #  800.4 KB\n",
    "pickle.dump(b, open('bit_tensor', 'wb'))    #  25.1 KB"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
